package com.sun2.booksotong.service.user;

import org.apache.commons.lang3.RandomStringUtils;

import com.sun2.booksotong.dao.user.Dao4User;
import com.sun2.booksotong.exception.user.Exception4User;
import com.sun2.booksotong.exception.user.Exception4User.USER_EXCEPTION;
import com.sun2.booksotong.model.user.Model4User;

public class Service4UserImpl implements Service4User {

	private Dao4User dao4User;

	public void setDao4User(Dao4User dao4User) {
		this.dao4User = dao4User;
	}

	@Override
	public void singup(String account, String name, String password) throws Exception {
		Model4User aaa = dao4User.readUserByAccount(account);
		if (aaa != null) {
			throw new Exception4User(USER_EXCEPTION.DUPLICATE_ACCOUNT);
		}
		dao4User.createUser(new Model4User(account, name, password));
	}
	
	@Override
	public void forgot(String account) throws Exception {
		Model4User aaa = dao4User.readUserByAccount(account);
		if (aaa == null) {
			throw new Exception4User(USER_EXCEPTION.NOT_EXIST_ACCOUNT);
		}
		String password = RandomStringUtils.randomAlphabetic(32);
		aaa.setPassword(password);
		dao4User.updateUser(aaa);
		// TODO: email 전송
	}

	@Override
	public int login(String account, String password) throws Exception {
		Model4User aaa = dao4User.readUserByAccount(account);
		if (aaa == null) {
			throw new Exception4User(USER_EXCEPTION.NOT_EXIST_ACCOUNT);
		}
		if (aaa.getPassword().equals(password)) {
			throw new Exception4User(USER_EXCEPTION.NO_MATCH_PASSWORD);
		}
		return aaa.getNum();
	}

	@Override
	public Model4User profile(int num) throws Exception {
		return dao4User.readUserByNum(num);
	}

	@Override
	public Model4User setting(Model4User model4User) throws Exception {
		int num = model4User.getNum();
		Model4User aaa = dao4User.readUserByNum(num);
		if (aaa == null) {
			throw new Exception4User(USER_EXCEPTION.NOT_EXIST_ACCOUNT);
		}
		String password = model4User.getPassword();
		if (password == null || password.equals("")) {
			model4User.setPassword(aaa.getPassword());
		}
		dao4User.updateUser(model4User);
		return dao4User.readUserByNum(num);
	}

	@Override
	public void revoke(int num, String password) throws Exception {
		Model4User aaa = dao4User.readUserByNum(num);
		if (aaa.getPassword().equals(password)) {
			dao4User.deleteUser(num);
		}
	}

}
